package com.keepsoft.study.modules.share.controller;

import com.github.pagehelper.PageInfo;
import com.keepsoft.study.modules.share.model.ItemContent;
import com.keepsoft.study.modules.share.model.ItemType;
import com.keepsoft.study.modules.share.service.ItemContentService;
import com.keepsoft.study.modules.share.service.ItemTypeService;
import com.xiaoleilu.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @author liuyang
 * @desc 首页
 **/
@Controller
@RequestMapping("/share")
public class IndexController {
    /**
     * 默认页为1
     */
    protected static final Integer PAGENUM = 1;
    /**
     * 页码大小10
     */
    protected static final Integer PAGESIZE = 10;

    private static  String  BASEPATH="share/";

    @Autowired
    private ItemTypeService itemTypeService;

    @Autowired
    private ItemContentService itemContentService;
    @GetMapping({"","/index"})
    public String index(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,String typeId,ModelMap modelMap) throws Exception {

        List<ItemType> itemTypeList=itemTypeService.findAll();
        String jsonStr = JSONUtil.toJsonStr(itemTypeList);
        modelMap.put("itemTree",jsonStr);
        return BASEPATH+"index";
    }


    @GetMapping("/data")
    @ResponseBody
    public Object getData(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,String typeId,ModelMap modelMap) throws Exception {
        PageInfo<HashMap<String,Object>> pageInfo=itemTypeService.findPage(pageNum,PAGESIZE,typeId);
        return pageInfo;
    }

    @GetMapping("/add")
    public String addShow(String typeId,String typeName,ModelMap map){
        map.put("typeId",typeId);
        map.put("typeName",typeName);
        return BASEPATH+"share_add";
    }

    @ResponseBody
    @PostMapping(value = "")
    public ModelMap saveData(ItemContent model){
        ModelMap messagesMap = new ModelMap();

        int result = itemContentService.saveSelective(model);
        if (result > 0) {

            messagesMap.put("status", "success");
            messagesMap.put("message", "添加成功!");
            return messagesMap;
        }
        messagesMap.put("status", "falure");
        messagesMap.put("message", "添加失败!");
        return messagesMap;
    }


}
